<?php
namespace app\home\controller;
use think\Controller;
use think\Db;

class WeiXin extends Controller{

	 public function index(){

           $info = Db::name('wx_user')->find();
           if(!$info) $this->error("没有微信公众号");
           $w_token = $info['w_token'];
              define("TOKEN", $w_token);
         if (!isset($_GET['echostr'])) {
             $this->responseMsg();
         }else{
             $this->valid();
         }
     }

    private function valid(){
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }
    public function responseMsg()
    {
        //获取POST数据，可能是由于不同的环境
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //extract post data
        if (empty($postStr))
            exit("");

        /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
           the best way is to check the validity of xml by yourself */
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();

        //点击菜单拉取消息时的事件推送
        /*
         * 1、click：点击推事件
         * 用户点击click类型按钮后，微信服务器会通过消息接口推送消息类型为event的结构给开发者（参考消息接口指南）
         * 并且带上按钮中开发者填写的key值，开发者可以通过自定义的key值与用户进行交互；
         */
        if($postObj->MsgType == 'event' && $postObj->Event == 'CLICK')
        {
            $keyword = trim($postObj->EventKey);
        }
        if($postObj->MsgType == 'event' && $postObj->Event == 'subscribe')
        {
            $contentStr = "欢迎关注海南百和信息科技有限公司";
            $contentStr .= (!empty($postObj->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$postObj->EventKey)):"";
            $this->transmitText($contentStr,$fromUsername,$toUsername,$time);
        }

        if(empty($keyword))
            exit("Input something...");

        // 图文回复
        $wx_img = Db::name('wx_img')->where("keyword like '%$keyword%'")->find();
        if($wx_img)
        {
            $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <ArticleCount><![CDATA[%s]]></ArticleCount>
                                <Articles>
                                    <item>
                                        <Title><![CDATA[%s]]></Title>
                                        <Description><![CDATA[%s]]></Description>
                                        <PicUrl><![CDATA[%s]]></PicUrl>
                                        <Url><![CDATA[%s]]></Url>
                                    </item>
                                </Articles>
                                </xml>";
            $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,'news','1',$wx_img['title'],$wx_img['desc']
                , $wx_img['pic'], $wx_img['url']);
            exit($resultStr);
        }

        // 文本回复
        $wx_text = Db::name('wx_text')->where("keyword like '%$keyword%'")->find();
        if($wx_text)
        {
            $contentStr = $wx_text['text'];
            $this->transmitText($contentStr,$fromUsername,$toUsername,$time);
        }

        // 其他文本回复
        $contentStr = "你好，欢迎您";
        $this->transmitText($contentStr,$fromUsername,$toUsername,$time);

    }
    // 文本回复函数
    private function transmitText($contentStr, $fromUsername, $toUsername, $time){

        $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";

        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
        exit($resultStr);
    }
}